package vip.liux.backend.adapter.web;

import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import vip.liux.backend.application.service.pay.PayWalletRechargeService;
import vip.liux.backend.application.service.pay.dto.notify.PayNotifyResp;
import vip.liux.backend.application.service.pay.dto.notify.PayOrderNotifyDto;
import vip.liux.backend.application.service.pay.dto.notify.PayRefundNotifyDto;
import vip.liux.core.current.ICurrentUser;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Optional;

import static vip.liux.backend.infrastructure.utils.ServletUtil.getClientIP;

@RestController
@RequestMapping("/api/pay/wallet/recharge")
public class PayWalletRechargeController {

    @Resource
    private PayWalletRechargeService walletRechargeService;
    @Resource
    private ICurrentUser<Long> currentUser;

    /**
     * 发起钱包充值退款
     *
     * @param payPrice 充值金额
     * @param uid      用户编号（可选，默认为当前用户）
     */
    @PostMapping
    public void createWalletRecharge(@RequestParam("payPrice") BigDecimal payPrice, @RequestParam(value = "uid", required = false) String uid) {
        walletRechargeService.createWalletRecharge(
                Optional.ofNullable(uid).orElse(String.valueOf(currentUser.getId())),
                getClientIP(),
                payPrice
        );
    }

    /**
     * 更新钱包充值为已充值
     * 由支付服务进行回调
     *
     * @param notifyReqDTO 通知请求数据传输对象
     */
    @PostMapping("/paid")
    public PayNotifyResp updateWalletRechargerPaid(@Valid @RequestBody PayOrderNotifyDto notifyReqDTO) {
        walletRechargeService.updateWalletRechargerPaid(Long.valueOf(notifyReqDTO.getMerchantOrderId()), notifyReqDTO.getPayOrderNo());
        return new PayNotifyResp("success", 0);
    }

    /**
     * 更新钱包充值为已充值
     * 由支付服务进行回调
     *
     * @param notifyReqDTO 通知请求数据传输对象
     */
    @PostMapping("/refunded")
    public PayNotifyResp updateWalletRechargeRefunded(@Valid @RequestBody PayRefundNotifyDto notifyReqDTO) {
        walletRechargeService.updateWalletRechargeRefunded(
                Long.valueOf(notifyReqDTO.getMerchantOrderId()),
                Long.valueOf(notifyReqDTO.getMerchantRefundId()),
                notifyReqDTO.getPayRefundNo());
        return new PayNotifyResp("success", 0);
    }

    /**
     * 发起钱包充值退款
     *
     * @param id 钱包充值编号
     */
    @PostMapping("/refund")
    public void refundWalletRecharge(@RequestParam("id") Long id) {
        walletRechargeService.refundWalletRecharge(id, getClientIP());
    }
}